package org.ykhl.appserver.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ykhl.appserver.model.MessageInfo;
import org.ykhl.mq.util.HttpUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ValidateService {
    private static final Logger LOG = LoggerFactory.getLogger(ValidateService.class);
    private final String apiUrl;
    private HttpUtil httpUtil = new HttpUtil();
    private  MessageInfo messageInfo = new MessageInfo();
    private boolean hasPermission;
    private Map<String, Object> parameters = new HashMap<>();
    private String hasPerUrl =  "/api/dispatch/hasPermission";

    public ValidateService(String apiUrl) {
        Objects.requireNonNull(apiUrl, "ApiUrl can't be null");
        this.apiUrl = apiUrl;
    }

    /**
     * 判断接入方是否有权限
     * @param apperverId
     * @param fid
     * @param deviceSign
     * @return
     */
    public MessageInfo isPermissison(String apperverId, String fid, String deviceSign){

        try {
             hasPermission = getHasPermission(fid,apperverId,deviceSign);
            if(hasPermission){
                messageInfo.setCode(1);
                messageInfo.setMessage("允许访问");
            }else{
                messageInfo.setCode(0);
                messageInfo.setMessage("资源没有访问权限！");
            }
        }catch (Exception e){
            messageInfo.setCode(0);
            messageInfo.setMessage(e.getMessage());
        }
        return messageInfo;
    }

    /**
     * 判断该应用的该资源是否有权限调用
     *
     * @param resid
     * @param appid
     * @return
     */
    public boolean getHasPermission(String resid, String appid,String devicesign) {

        LOG.debug("getHasPermission - " + apiUrl + hasPerUrl + "?resid=" + resid + "&appid=" + appid +"&devicesign=" + devicesign);
        parameters.put("resid", resid);
        parameters.put("appid", appid);
        parameters.put("devicesign", devicesign);
        try {
            String resp = httpUtil.post(apiUrl + hasPerUrl, parameters);
            JSONObject object = JSON.parseObject(resp);
            if (object.containsKey("content")) {

                return object.getBoolean("content");
            } else {
                LOG.error("getHasPermission is error--" + resp);
            }
        } catch (Exception e) {
            LOG.error("getHasPermission is Exception error--" + e.getMessage());
        }
        return false;
    }

}